package com.chaihu.core.base.service.front;

import com.alibaba.fastjson.JSON;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.context.IPageData;
import com.chaihu.utils.factory.ApplicationContextFactory;
import com.chaihu.utils.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.lang.reflect.Method;

/**
 * @author chaihu
 * @date 2021/10/20
 */
@Slf4j
public class BaseComponentService extends AppBase {

    /**
     * 调用组件
     *
     * @param componentCode   组件编码
     * @param componentMethod 组件方法
     * @param pd
     * @return
     */
    protected ResponseEntity<String> invokeComponent(String componentCode, String componentMethod, IPageData pd) {

        log.debug("开始调用组件：{}", pd.toString());

        ResponseEntity<String> responseEntity = null;

        Object componentInstance = ApplicationContextFactory.getBean(componentCode);

        Assert.notNull(componentInstance, "未找到组件对应的处理类，请确认 " + componentCode);
        try {

            Method cMethod = componentInstance.getClass().getDeclaredMethod(componentMethod, IPageData.class);

            Assert.notNull(cMethod, "未找到组件对应处理类的方法，请确认 " + componentCode + "方法：" + componentMethod);

            log.debug("组件编码{}，组件方法{}，pd 为{}", componentCode, componentMethod, pd.toString());

            responseEntity = (ResponseEntity<String>) cMethod.invoke(componentInstance, pd);
        } catch (Exception e) {
            log.error("调用组件失败：", e);
            ResponseResult result = new ResponseResult(MsgCode.ERROR.getCode(), "调用组件" + componentCode + ",组件方法" + componentMethod + "失败：" + e.getMessage());
            responseEntity = new ResponseEntity<String>(JSON.toJSONString(result), HttpStatus.OK);
        } finally {
            return responseEntity;
        }
    }
}
